<?php

/**
 * Enter description here ...
 * @author tiamsw
 *
 */
class CsvstorageController extends Controller{

	public function index(){
		$dbutil = $this->getMedooDb();
		
		$zipFile = PROJECT."/controller/admin/datas.zip";
		$outDir = PROJECT."/datas/";
		
		$zip = new ZipArchive;
		if ($zip->open($zipFile) === TRUE) {
		    $zip->extractTo($outDir);
		    $zip->close();
			
		    $files = array();
			$dir = dir($outDir);
			while($entry=$dir->read()){    
				if($entry == '.' || $entry == '..') {
					continue;    
				}
				//echo $outDir.$entry."<br>";
				$files[] = $outDir.$entry;
			}
			
			foreach ($files as $fileName){
				$table = "";
				
				if(strpos(":".$fileName,"games.csv") ){
					$table = "game";
				}else if(strpos(":".$fileName,"relation.csv") ){
					$table = "relations";
				}else if(strpos(":".$fileName,"tags.csv") ){
					$table = "tags";
				}
				
				if($table == ""){
				 	continue;
				}
				$sql = null;
				$colum = array();
				
				$file = fopen($fileName,'r'); 
				
				while ($data = fgetcsv($file)) { 
					
					if($sql == null){
						$cols = "";
						$format = "";
						foreach ($data as $col){
							$colName = $this->columGen($col);
							
							if($colName == null || $colName ==''){
								continue;
							}
							
							$colum[] = ':'.$colName;
							$cols = $cols.",".$colName;
							
							if( strpos(':'.$colName,'time') || strpos(':'.$colName,'date') ){
								$format = $format.",str_to_date(:".$colName.",'%a %b %d %H:%i:%s CST %Y')";
							}else{
								$format = $format.",:".$colName;
							}
						}
						$cols = substr($cols, 1);
						$format = substr($format, 1);
						$sql = " insert into ".$table." (".$cols.") value ( ".$format." ) ";
						continue;
					}
					
					$row = array();
					for($index = 0 ; $index < count($data) ; $index++){
						$colName = $colum[$index];
						$row[$colum[$index]] = $data[$index];
					}

					$dbutil->prepareUpdate($sql,$row);
				}
				fclose($file);
			}
		} 
		
		
	}
	
	
	public function columGen($colnum){
		preg_match_all('/([A-Z])/', $colnum ,$rr);  
		if ( count($rr) > 0){
			$r = $rr[0];
			foreach ( $r as $a){
				$colnum = str_replace($a,'_'.$a,$colnum);
			}
		}
		return strtolower($colnum);
	}
	
}